package whu.edu.demo.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import whu.edu.demo.dao.userDao;
import whu.edu.demo.domain.Role;
import whu.edu.demo.domain.Users;

import java.util.List;

/**
 * @author 86159
 */
@Service
public class DBservice implements UserDetailsService {

    @Autowired
    userDao user;

    @Cacheable(cacheNames = "UserDetail",key = "#username",condition = "#username!=null")
    public Users getUserDetail(String username){
        String pwd = user.getPasswordByUsername(username);
        if(pwd == null){return null;}
        else{ Users temp = new Users();
            temp.setUsername(username);
            temp.setPassword(pwd);
            return temp;
        }
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = getUserDetail(username);
        String password;
        if(users == null) {
            password = user.getPasswordByUsername(username);
            if (password == null) {
                throw new UsernameNotFoundException("没有找到用户" + username);
            }
        }
        else{
            password = users.getPassword();
        }
        IPage<Role> page = new Page<>(0,20);
        List<Role> roleList = user.getRolesByUsername(page,username).getRecords();
        String[] roles = new String[roleList.size()];
        for(int i =0;i<roles.length;i++){
            roles[i] = roleList.get(i).getName();
        }
        return User.builder().username(username).password(new BCryptPasswordEncoder().encode(password)).roles(roles).build();
    }
}